<?php
///
namespace lxsphp\Store\Pdo;

///
use lxsphp\App;

/**
 * 代表一个到数据库的Pdo连接。
 *
 * @version $Id: Pdo.php 191 2014-07-17 10:14:35Z linsir123 $
 * @package lxsphp\Store\Pdo
 */
class Pdo
{
	/**
	 * 配置
	 *
	 * @var array
	 */
	public $conf;

	/**
	 * @var \PDO
	 */
	private $_pdo;

	/**
	 * 构造函数
	 *
	 * @param array $conf 配置
	 *
	 * @throws \Exception
	 */
	public function __construct($conf)
	{
		///
		$this->conf = $conf;

		///
		$this->_connect();
	}

	/**
	 * 取得当前的PDO对象
	 *
	 * @return \PDO
	 */
	public function getPdo()
	{
		///
		return $this->_pdo;
	}

	/**
	 * 引用
	 *
	 * @param string $str
	 *
	 * @return string
	 */
	public function quoteValue($str)
	{
		///
		if (is_int($str) || is_float($str))
			return $str;

		return $this->_pdo->quote($str);
	}

	/**
	 * 引用
	 *
	 * @param string $name
	 *
	 * @return string
	 */
	public function quoteTableName($name)
	{
		///
		if (strpos($name, '.') === false)
			return '`' . $name . '`';

		///
		$parts = explode('.', $name);
		foreach ($parts as $i => $part)
			$parts[$i] = '`' . $part . '`';

		return implode('.', $parts);
	}

	/**
	 * 引用
	 *
	 * @param string $name
	 *
	 * @return string
	 */
	public function quoteColumnName($name)
	{
		///
		if (($pos = strrpos($name, '.')) !== false) {
			$prefix = $this->quoteTableName(substr($name, 0, $pos)) . '.';
			$name = substr($name, $pos + 1);
		}
		else
			$prefix = '';

		return $prefix . ($name === '*' ? $name : '`' . $name . '`');
	}

	/**
	 * 连接
	 *
	 * @throws \Exception
	 */
	private function _connect()
	{
		///
		App::$I->getDebugger()->timerStart();

		///
		try {
			$this->_pdo = new \PDO(
				$this->conf['dsn'],
				$this->conf['username'],
				$this->conf['password'],
				array(
					\PDO::ATTR_TIMEOUT => 5,
					\PDO::ATTR_EMULATE_PREPARES => false,
					\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
					\PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8';",
				)
			);
		} catch (\Exception $e) {
			///
		}

		///
		App::$I->getDebugger()->log(sprintf("[PDO] - Init: %s@%s",
			$this->conf['dsn'], $this->conf['username']));

		///
		if (isset($e))
			App::$I->getHandler()->panic($e);
	}
}
